package com.awei.aweiaiagent.advisor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.ai.chat.model.MessageAggregator;
import reactor.core.publisher.Flux;

@Slf4j
public class MyLoggerAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {


    /**
     * 对用户的请求进行增强
     * @param request AdvisedRequest包含了用户对AI的原始请求
     * @return 通常返回原始请求，也可以返回修改后的请求
     */
    private AdvisedRequest before(AdvisedRequest request) {
        //记录日志
        log.info("用户提示词{}", request.userText());
        return request;
    }

    /**
     * 返回响应后的ai的回答
     * @param advisedResponse 返回AI响应后的完整回答内容
     */
    private void after(AdvisedResponse advisedResponse) {
        //记录日志
        log.info("AI 响应结果{}", advisedResponse.response().getResult().getOutput().getText());
    }

    /**
     * 用于拦截非流式 AI 调用
     * @param advisedRequest
     * @param chain
     * @return
     */
    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        //调用before方法获取用户的请求
        advisedRequest = before(advisedRequest);
        //将请求传递给下一个拦截器或者实际的ai服务
        AdvisedResponse advisedResponse = chain.nextAroundCall(advisedRequest);
        //调用after方法记录ai的回答
        after(advisedResponse);
        return advisedResponse;
    }

    /**
     * 用于拦截流式 AI 调用
     * @param advisedRequest
     * @param chain
     * @return
     */
    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {

        //调用before方法获取用户的请求
        advisedRequest = before(advisedRequest);
        //获取一个流对象，这将会逐步发出生成的内容片段
        Flux<AdvisedResponse> advisedResponse = chain.nextAroundStream(advisedRequest);
        //把收到的流对象聚合在一起然后记录日志
        return new MessageAggregator().aggregateAdvisedResponse(advisedResponse, this::after);

    }

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
